﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Astronergy.MES.App.Library.Logger
{
    public class LogConsole : TraceListener
    {
        public static readonly LogConsole InstanceLogConsole = new LogConsole();
        private Logger _logger;

        public void Init(bool UserDebugOutput, bool UseCrForWriteLine, string sPath)
        {
            if (!Directory.Exists(sPath))
            {
                Directory.CreateDirectory(sPath);
            }
            _logger = new Logger(sPath, EnumLogType.Daily);
            if (UserDebugOutput)
            {
                Debug.Listeners.Add(this);
            }
            else
            {
                Trace.Listeners.Add(this);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (_logger != null))
            {
                _logger.Dispose();
                _logger = null;
            }
        }

        public override void WriteLine(object o)
        {
            var logMsg = o as LogMsg;
            if (logMsg != null)
            {
                var msg = logMsg;
                if (_logger != null)
                {
                    _logger.Write(msg);
                }
                Console.WriteLine(msg.ToString());
            }
        }        

        public override void WriteLine(string message, string category)
        {
            if (_logger != null)
            {
                _logger.Write(message, category);
            }
        }


        public override void WriteLine(string message)
        {
            if (_logger != null)
            {
                _logger.Write(message, EunmMsgType.Info);
            }
        }

        public override void Write(string message)
        {
            if (_logger != null)
            {
                _logger.Write(message, EunmMsgType.Info);
            }
        }
    }
}
